<script setup>
import { getUsers, addUser, editUser, deleteUser } from "@/api/user";
import { showConfirmDialog } from "vant";

const list = ref([]);

const show = ref(false);
const form = reactive({
  code: "",
  remark: "",
});
const formRef = ref();
const showDialog = (el = {}) => {
  Object.assign(form, {
    id: el.id,
    code: el.code,
    remark: el.remark,
  });
  show.value = true;
};
const handleSave = (action) => {
  if (action === "confirm") {
    return formRef.value
      ?.validate()
      ?.then(() => {
        return form.id ? editUser(form.id, form) : addUser(form);
      })
      .then(() => {
        fetchData();
        return true;
      })
      .catch((err) => {
        return false;
      });
  }
  return true;
};

const handleDelete = (el) => {
  showConfirmDialog({
    title: "提示",
    message: "确定删除吗？",
  })
    .then(() => deleteUser(el.code))
    .then(() => fetchData());
};

const fetchData = () => {
  getUsers().then((res) => {
    list.value = res;
  });
};

onMounted(() => {
  fetchData();
});
</script>

<template>
  <div>
    <van-swipe-cell v-for="el of list" :key="el.id">
      <van-cell
        :title="el.code"
        :label="el.remark"
        is-link
        center
        :to="{ path: `/device`, query: { uid: el.id } }"
      />
      <template #right>
        <van-button square type="primary" text="编辑" @click="showDialog(el)" />
        <van-button
          square
          type="danger"
          text="删除"
          @click="handleDelete(el)"
        />
      </template>
    </van-swipe-cell>
    <van-floating-bubble icon="plus" @click="showDialog()" />

    <van-dialog
      v-model:show="show"
      :title="form.id ? '编辑用户' : '添加用户'"
      show-cancel-button
      :before-close="handleSave"
    >
      <van-form ref="formRef" :model="form" label-width="3em">
        <van-field
          v-model="form.code"
          name="code"
          label="编码"
          placeholder="请输入编码"
          :rules="[{ required: true, message: '请输入编码' }]"
        />
        <van-field
          v-model="form.remark"
          name="remark"
          label="备注"
          placeholder="请输入备注"
        />
      </van-form>
    </van-dialog>
  </div>
</template>

<style lang="scss" scoped>
:deep() {
  .van-swipe-cell__right .van-button {
    height: 100%;
  }
}
</style>
